import React, { useState, useEffect, useCallback } from 'react';
import {
  Table,
  Tag,
  Space,
  Button,
  Switch,
  Modal,
  Input,
  Form,
  Rate,
} from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import BookDrawer from './BookDrawer';
import BookDetails from './BookDetails';

const tagColors = [
  'magenta',
  'red',
  'volcano',
  'orange',
  'gold',
  'lime',
  'green',
  'cyan',
  'blue',
  'geekblue',
  'purple',
];
const getRandomTagColor = () => {
  const randomIndex = Math.floor(Math.random() * tagColors.length);
  return tagColors[randomIndex];
};
const ReadManager = () => {
  const [books, setBooks] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });
  const [filterModalVisible, setFilterModalVisible] = useState(false);
  const [filterValues, setFilterValues] = useState({});
  const [loading, setLoading] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [drawerMode, setDrawerMode] = useState('add');
  const [drawerRecord, setDrawerRecord] = useState(null); // 添加这一行定义
  const [bookDetailsVisible, setBookDetailsVisible] = useState(false);
  const [selectedBook, setSelectedBook] = useState(null);
  const showBookDetails = book => {
    setSelectedBook(book);
    setBookDetailsVisible(true);
  };

  const openDrawer = (mode, book) => {
    setDrawerMode(mode);
    setDrawerRecord(book || null);
    setDrawerVisible(true);
  };
  const clearFilterValues = () => {
    setFilterValues({});
    form.resetFields();
  };
  const deleteBook = async bookId => {
    const token = sessionStorage.getItem('token');
    const requestOptions = {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
    };

    try {
      const response = await fetch(
        `http://localhost:29157/api/book/list/${bookId}?token=${token}`,
        requestOptions
      );
      const data = await response.json();

      if (data.status) {
        // 刷新书籍列表
        refreshBooks();
      } else {
        console.error('Error deleting book:', data.error);
      }
    } catch (error) {
      console.error('Error deleting book:', error.message);
    }
  };
  const fetchBooks = useCallback(async (pagination, filterValues) => {
    setLoading(true);
    const token = sessionStorage.getItem('token'); // 根据您的实际应用程序从本地存储或其他位置获取令牌
    const requestOptions = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
    };

    try {
      const response = await fetch(
        `http://localhost:29157/api/book/list?token=${token}&page=${
          pagination.current
        }&pageSize=${pagination.pageSize}&keywords=${
          Object.keys(filterValues).length === 0
            ? ''
            : encodeURIComponent(JSON.stringify(filterValues))
        }`,
        requestOptions
      ).finally(setLoading(false));
      const data = await response.json();

      if (data.status) {
        setBooks(data.data.books);
      } else {
        console.error('Error fetching books:', data.error);
      }
    } catch (error) {
      console.error('Error fetching books:', error.message);
    }
  });
  const refreshBooks = () => {
    fetchBooks(pagination, filterValues);
  };
  useEffect(() => {
    fetchBooks(pagination, filterValues);
  }, [pagination, filterValues]);

  const [form] = Form.useForm();

  const columns = [
    {
      title: '书名',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <a
          onClick={() => {
            setSelectedBook(record);
            setBookDetailsVisible(true);
          }}>
          {text}
        </a>
      ),
    },

    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      render: tags => (
        <Space>
          {tags.split(',').map(tag => (
            <Tag
              color={getRandomTagColor()}
              key={tag}>
              {tag}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: status => (
        <span
          style={{
            color:
              status === '待阅读'
                ? 'red'
                : status === '已阅读'
                ? 'green'
                : 'blue',
            fontWeight: 'bold',
          }}>
          {status}
        </span>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '时间',
      dataIndex: 'date',
      key: 'date',
      render: date => new Date(date).toLocaleString(),
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      render: rating => {
        if (rating) {
          return (
            <Rate
              value={rating}
              disabled
              allowHalf
            />
          );
        } else {
          return '-';
        }
      },
    },

    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size='middle'>
          <Button
            icon={<EditOutlined />}
            onClick={() => openDrawer('edit', record)}>
            编辑
          </Button>
          <Button
            icon={<DeleteOutlined />}
            onClick={() => {
              Modal.confirm({
                title: '确认删除',
                content: '你确定要删除这本书吗？',
                okText: '确定',
                cancelText: '取消',
                onOk: () => {
                  console.log('Delete', record);
                  deleteBook(record.id);
                },
              });
            }}>
            删除
          </Button>
          <Switch
            checked={record.isPublic === 1}
            onChange={() => console.log('Toggle public', record)}
          />
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '16px',
        }}>
        <h2>阅读管理</h2>
        <span style={{ fontSize: '14px', fontStyle: 'italic', color: 'gray' }}>
          点击书名，将会弹出详情页哦(操作列的小按钮请无视，功能将在后续版本实现)
        </span>
        <div>
          <Button
            type='primary'
            style={{ marginRight: '8px' }}
            onClick={() => openDrawer('add')}>
            新增
          </Button>
          <Button
            type='primary'
            style={{ marginRight: '8px' }}
            onClick={() => setFilterModalVisible(true)}>
            筛选
          </Button>

          <Button
            type='primary'
            onClick={() => console.log('导出书单')}>
            导出书单
          </Button>
        </div>
      </div>
      <Table
        columns={columns}
        dataSource={books}
        rowKey='id'
        pagination={{
          ...pagination,
          showSizeChanger: true,
          pageSizeOptions: ['7', '10', '15'],
        }}
        loading={loading}
        onChange={pagination => setPagination(pagination)}
      />

      <Modal
        title='筛选'
        visible={filterModalVisible}
        onCancel={() => setFilterModalVisible(false)}
        footer={[
          <Button
            key='clear'
            onClick={() => {
              clearFilterValues();
              fetchBooks(pagination, {});
              setFilterModalVisible(false);
            }}>
            清除筛选条件
          </Button>,
          <Button
            key='cancel'
            onClick={() => setFilterModalVisible(false)}>
            取消
          </Button>,
          <Button
            key='submit'
            type='primary'
            onClick={() => {
              form
                .validateFields()
                .then(values => {
                  const filledValues = Object.fromEntries(
                    Object.entries(values).filter(([, value]) => value)
                  );
                  setFilterValues(filledValues);
                  setFilterModalVisible(false);
                  fetchBooks(pagination, filledValues);
                })
                .catch(info => {
                  console.log('Validate Failed:', info);
                });
            }}>
            确定
          </Button>,
        ]}>
        <Form
          form={form}
          layout='vertical'>
          <Form.Item
            label='书名'
            name='title'>
            <Input placeholder='请输入书名' />
          </Form.Item>
          <Form.Item
            label='标签'
            name='tags'>
            <Input placeholder='请输入标签' />
          </Form.Item>
          <Form.Item
            label='类型'
            name='type'>
            <Input placeholder='请输入类型' />
          </Form.Item>
          <Form.Item
            label='状态'
            name='status'>
            <Input placeholder='请输入状态' />
          </Form.Item>
        </Form>
      </Modal>
      <BookDrawer
        visible={drawerVisible}
        mode={drawerMode}
        fetchData={refreshBooks}
        onClose={() => setDrawerVisible(false)}
        onConfirm={values => {
          console.log('Submitted values:', values);
          setDrawerVisible(false);
        }}
        book={drawerMode === 'edit' ? drawerRecord : null}
      />
      <BookDetails
        visible={bookDetailsVisible}
        onClose={() => setBookDetailsVisible(false)}
        book={selectedBook}
      />
    </div>
  );
};

export default ReadManager;
